var webim = require('../../resource/js/chat/webim.js');
var webimhandler = require('../../resource/js/chat/webim_handler.js');
var tls = require('../../resource/js/chat/tls.js');

var app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        siteInfo: app.siteInfo,
        focus: false,
        playing: false,
        frontCamera: true,
        cameraContext: {},
        pushUrl: "",
        showHDTips: false, //显示清晰度弹窗
        mode: "HD",
        muted: false,
        enableCamera: true,
        orientation: "vertical",
        beauty: 6.3,
        whiteness: 3.0,
        backgroundMute: false,
        hide: false,
        debug: false,
        playUrl: "",
    },

    onInputTap: function () {
        this.setData({
            focus: true
        })
    },

    // input框内容同步到js
    onInputChange: function (e) {
        this.setData({
            pushUrl: e.detail.value,
            playUrl: "",
        })
    },

    onScanQR: function () {
        this.stop();
        console.log("onScaneQR");
        var self = this;
        wx.scanCode({
            onlyFromCamera: true,
            success: (res) => {
                console.log(res);
                self.setData({
                    pushUrl: res.result,
                    playUrl: "",
                })
                wx.showToast({
                    title: '获取地址成功',
                })

            }
        })
    },

    onNewUrlClick: function () {
        var that = this;
        //用户信息
        app.util.request({
            'url': 'player/getLivePlayer',
            'showLoading': true,
            'data': {'id': that.data.live_id},
            success: function (res) {
                var data = res.data.data;
                that.setData({
                    pushUrl: data.url_push,
                    playUrl: data.url_play_flv,
                })
            },
            fail: (res) => {
                console.log(res);
                wx.showToast({
                    title: '网络或服务器异常',
                })
            }
        });
    },

    onPushClick: function () {
        // this.data.pusherConfig.debug = !this.data.pusherConfig.debug;
        var that = this;
        if (this.data.pushUrl.indexOf("rtmp://") != 0) {
            wx.showModal({
                title: '提示',
                content: '推流地址不合法，请点击右上角+按钮先获取腾讯云推流地址',
                showCancel: false
            });
            return;
        }
        this.setData({
            playing: !this.data.playing,
        })
        if (this.data.playing) {
            this.data.cameraContext.start();
            console.log("camera start");
        } else {
            this.data.cameraContext.stop();
            console.log("camera stop");
        }
        that.upAnchorStat();
    },
    upAnchorStat: function () {
        if (this.data.playing) {
            var status = 1;
            //主播上线
        } else {
            var status = 0;
        }
        var that = this;
        app.util.request({
            'url': 'player/upLiveStatus',
            'showLoading': true,
            'data': {'id': that.data.live_id, 'status': status},
            success: function (res) {
            },
            fail: (res) => {
                console.log(res);
                wx.showToast({
                    title: '网络或服务器异常',
                })
            }
        });
    },

    onSwitchCameraClick: function () {
        this.data.frontCamera = !this.data.frontCamera;
        this.setData({
            frontCamera: this.data.frontCamera
        })
        this.data.cameraContext.switchCamera();
    },

    onBeautyClick: function () {
        if (this.data.beauty != 0) {
            this.data.beauty = 0;
            this.data.whiteness = 0;
        } else {
            this.data.beauty = 6.3;
            this.data.whiteness = 3.0;
        }

        this.setData({
            beauty: this.data.beauty,
            whiteness: this.data.whiteness
        })
    },

    onOrientationClick: function () {
        if (this.data.orientation == "vertical") {
            this.data.orientation = "horizontal";
        } else {
            this.data.orientation = "vertical";
        }
        this.setData({
            orientation: this.data.orientation
        })
    },

    onLogClick: function () {
        this.setData({
            debug: !this.data.debug
        })
    },
    onSwitchMode: function () {
        var showTips = !this.data.showHDTips;
        this.setData({
            showHDTips: showTips
        })
    },
    onModeClick: function (event) {
        var mode = "SD";
        switch (event.target.dataset.mode) {
            case "SD":
                mode = "SD";
                break;
            case "HD":
                mode = "HD";
                break;
            case "FHD":
                mode = "FHD";
                break;
        }

        this.setData({
            mode: mode,
            showHDTips: false
        })
    },

    onEnableCameraClick: function () {
        this.setData({
            enableCamera: !this.data.enableCamera
        })
        if (this.data.playing) {
            this.data.cameraContext.stop();
            setTimeout(() => {
                this.data.cameraContext.start();
            }, 500)
        }
    },

    onMuteClick: function () {
        this.setData({
            muted: !this.data.muted
        })
    },

    onPushEvent: function (e) {
        console.log(e.detail.code);

        if (e.detail.code == -1307) {
            this.stop();
            wx.showToast({
                title: '推流多次失败',
            })
        }
    },

    stop: function () {
        var that = this;
        this.setData({
            playing: false,
            //pushUrl: "rtmp://2157.livepush.myqcloud.com/live/2157_wx_live_test1?bizid=2157&txSecret=7b0391fa4d9956a54d1a8238bc358372&txTime=5A071E7F",
            mode: "HD",
            muted: false,
            enableCamera: true,
            orientation: "vertical",
            beauty: 6.3,
            whiteness: 3.0,
            backgroundMute: false,
            debug: false
        })
        this.data.cameraContext.stop();
        that.upAnchorStat(0);
    },

    createContext: function () {
        this.setData({
            cameraContext: wx.createLivePusherContext('camera-push'),
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        wx.createLivePlayerContext('live-player').stop();//关闭
        var id = that.options.live_id;
        that.setData({
            'live_id': id,
        });
        //获取直播间直播地址
        app.util.request({
            'url': 'player/getLivePlayer',
            'data': {'id': id},
            success: function (res) {
                var data = res.data.data;
                that.setData({
                    pushUrl: data.url_push,
                    playUrl: data.url_play_flv,
                });
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log("onLoad onReady");
        this.createContext();

        wx.setKeepScreenOn({
            keepScreenOn: true,
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this;
        that.requestInitIM();
        console.log("onLoad onShow");
        // 保持屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: true
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.logoutIM();
        wx.setKeepScreenOn({
            keepScreenOn: false,
        })
        console.log("onLoad onHide");
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.logoutIM();
        console.log("onLoad onUnload");
        this.stop();
        wx.setKeepScreenOn({
            keepScreenOn: false,
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        console.log("onLoad onPullDownRefresh");

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        console.log("onLoad onReachBottom");

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        console.log("onLoad onShareAppMessage");
        return {
            // title: 'RTMP推流',
            // path: '/pages/push/push',
            path: '/pages/main/main',
            imageUrl: 'https://mc.qcloudimg.com/static/img/dacf9205fe088ec2fef6f0b781c92510/share.png'
        }
    },

    /***
     * 显示播放二维码
     */
    onPlayQRClick: function () {
        if (!this.data.playUrl) {
            wx.showModal({
                title: '提示',
                content: '播放地址不合法，请点击右上角+按钮先获取腾讯云推流地址',
                showCancel: false
            });
            return;
        }

        var url = './playqr/playqr?playUrl=' + this.data.playUrl;
        wx.navigateTo({
            url: url
        });
    },
    //聊天接受消息
    receiveMsgs: function (data) {
        var that = this;
        var msgs = this.data.msgs || [];
        var content = data.content;

        var reg = /群提示消息/ig;
        if (reg.test(content)) {
            return;
        }

        var pattern = /data\=(.*?)\,\s+desc\=(.*?)\,\s+ext\=(.*)/i;
        var martchRet = content.match(pattern);

        if (!martchRet) {
            return;
        }
        var ext = martchRet[3];
        ext = JSON.parse(ext);
        var live_id = ext.live_id;
        var nickname = ext.nickname;

        if (live_id != that.data.live_id) {
            return;
        }

        data.content = martchRet[1];
        data.fromAccountNick = nickname;

        msgs.push(data);
        if (msgs.length > 8) {
            msgs = msgs.slice(-8)
        }
        //最多展示8条信息
        if (msgs.length > 8) {
            msgs.splice(0, msgs.length - 8)
        }
        //过滤掉
        this.setData({
            msgs: msgs,
            'bottom_scroll_top': this.data.bottom_scroll_top + 50,
        })
    },
    requestInitIM: function () {
        var that = this;
        app.util.getUserInfo(function (res) {
            var userInfo = res.memberInfo;
            that.setData({
                userInfo: userInfo,
            });
            app.util.request({
                'url': 'live/getChatConfig',
                'cachetime': '60',
                success: function (res) {
                    var data = res.data.data;
                    that.setData({
                        'chat': data,
                    });
                    var Config = {
                        sdkappid: data.sdk_appid
                        , accountType: data.account_type
                        , accountMode: 1 //帐号模式，0-表示独立模式，1-表示托管模式
                    };
                    that.setData({
                        'avChatRoomId': data.room_id,
                        'Identifier': data.identifier,
                        'UserSig': data.user_sig,
                    });
                    tls.init({
                        sdkappid: data.sdk_appid
                    })
                    that.initIM(userInfo, Config);
                }
            });
        });
    },
    logoutIM: function () {
        webimhandler.logout();
    },
    initIM: function (userInfo, Config) {
        var that = this;

        var avChatRoomId = that.data.avChatRoomId;
        webimhandler.init({
            accountMode: Config.accountMode
            , accountType: Config.accountType
            , sdkAppID: Config.sdkappid
            , avChatRoomId: avChatRoomId //默认房间群ID，群类型必须是直播聊天室（AVChatRoom），这个为官方测试ID(托管模式)
            , selType: webim.SESSION_TYPE.GROUP
            , selToID: avChatRoomId
            , selSess: null //当前聊天会话
        });
        //当前用户身份
        var loginInfo = {
            'sdkAppID': Config.sdkappid, //用户所属应用id,必填
            'appIDAt3rd': Config.sdkappid, //用户所属应用id，必填
            'accountType': Config.accountType, //用户所属应用帐号类型，必填
            'identifier': that.data.Identifier, //当前用户ID,必须是否字符串类型，选填
            'identifierNick': userInfo.nickname, //当前用户昵称，选填
            'userSig': that.data.UserSig, //当前用户身份凭证，必须是字符串类型，选填
            'live_id': that.data.live_id, //直播间id
        };

        //监听（多终端同步）群系统消息方法，方法都定义在demo_group_notice.js文件中
        var onGroupSystemNotifys = {
            "5": webimhandler.onDestoryGroupNotify, //群被解散(全员接收)
            "11": webimhandler.onRevokeGroupNotify, //群已被回收(全员接收)
            "255": webimhandler.onCustomGroupNotify//用户自定义通知(默认全员接收)
        };

        //监听连接状态回调变化事件
        var onConnNotify = function (resp) {
            switch (resp.ErrorCode) {
                case webim.CONNECTION_STATUS.ON:
                    //webim.Log.warn('连接状态正常...');
                    break;
                case webim.CONNECTION_STATUS.OFF:
                    webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
                    break;
                default:
                    webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
                    break;
            }
        };

        //监听事件
        var listeners = {
            "onConnNotify": webimhandler.onConnNotify, //选填
            "onBigGroupMsgNotify": function (msg) {
                webimhandler.onBigGroupMsgNotify(msg, function (msgs) {
                    that.receiveMsgs(msgs);
                })
            }, //监听新消息(大群)事件，必填
            "onMsgNotify": webimhandler.onMsgNotify,//监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
            "onGroupSystemNotifys": webimhandler.onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
            "onGroupInfoChangeNotify": webimhandler.onGroupInfoChangeNotify//监听群资料变化事件，选填
        };

        //其他对象，选填
        var options = {
            'isAccessFormalEnv': true,//是否访问正式环境，默认访问正式，选填
            'isLogOn': false//是否开启控制台打印日志,默认开启，选填
        };

        if (Config.accountMode == 1) {//托管模式
            webimhandler.sdkLogin(loginInfo, listeners, options, avChatRoomId);
        } else {//独立模式
            //sdk登录
            webimhandler.sdkLogin(loginInfo, listeners, options);
        }
    },
})